<template>
  <div class="party-container">
    <el-card class="party-card">
      <template #header>
        <div class="card-header">
          <h3>当事人管理</h3>
        </div>
      </template>

      <el-form :model="queryForm" :inline="true" @submit.prevent="handleQuery" class="mb-4">
        <el-form-item label="关键词">
          <el-input v-model="queryForm.keywords" placeholder="姓名/证件号/联系方式" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loading"
        :data="partyList"
        style="width: 100%"
        height="calc(100vh - 330px)"
        border
        header-row-class-name="table-header-row"
        row-class-name="table-row"
      >
        <el-table-column
          prop="name"
          label="当事人姓名"
          width="140"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="idcard"
          label="证件号"
          width="180"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="phone"
          label="联系电话"
          width="140"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="party_type_name"
          label="个人/企业"
          width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="create_time"
          label="创建时间"
          width="160"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">查看详情</el-button>
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.page"
          v-model:page-size="queryForm.limit"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="当事人详情"
      :direction="'rtl'"
      :size="'80%'"
      :with-header="true"
    >
      <div class="drawer-content">
        <el-descriptions border :column="1" class="mb-4">
          <el-descriptions-item label="当事人姓名">{{ detailForm.name }}</el-descriptions-item>
          <el-descriptions-item label="证件号">{{ detailForm.idcard }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ detailForm.phone || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="地址">{{ detailForm.address || '-' }}</el-descriptions-item>
          <el-descriptions-item label="个人/企业">
            {{ detailForm.party_type_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ detailForm.create_time }}</el-descriptions-item>
        </el-descriptions>

        <div class="related-cases">
          <h4 class="mb-3">参与案件</h4>
          <el-table
            v-loading="casesLoading"
            :data="relatedCases"
            style="width: 100%"
            border
            header-row-class-name="table-header-row"
            row-class-name="table-row"
            height="calc(100vh - 500px)"
          >
            <el-table-column
              prop="case_code"
              label="案件编号"
              width="150"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="status_text"
              label="当前进度"
              width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column prop="is_client_text" label="委托身份" width="100" align="center">
              <template #default="{ row }">
                <el-tag
                  v-if="row.is_client_text"
                  :type="row.is_client === 1 ? 'success' : 'info'"
                  size="small"
                >
                  {{ row.is_client_text }}
                </el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="委托人" width="180" show-overflow-tooltip>
              <template #default="{ row }">
                <div class="cell-ellipsis">
                  {{ row.clients || '-' }}
                  <span v-if="row.clients && row.relationship_text">
                    ({{ row.relationship_text }})
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="对方当事人" width="180" show-overflow-tooltip>
              <template #default="{ row }">
                <div class="cell-ellipsis">
                  {{ row.opponents || '-' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="main_lawyer_name"
              label="主办律师"
              width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="secondary_lawyer_name"
              label="管家"
              width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="session_lawyer_name"
              label="出庭律师"
              width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column label="开庭日期" width="120" show-overflow-tooltip>
              <template #default="{ row }">
                {{ row.session_time ? formatDate(row.session_time) : '-' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="contract_id"
              label="合同ID"
              width="100"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="entrust_date"
              label="接案日期"
              width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="stage"
              label="代理阶段"
              width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="case_type_text"
              label="案件类型"
              width="120"
              show-overflow-tooltip
            ></el-table-column>
          </el-table>
        </div>
      </div>
    </el-drawer>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="证件号" prop="idcard">
          <el-input v-model="form.idcard" placeholder="请输入证件号" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import {
    ElMessage,
    ElMessageBox,
    ElDrawer,
    ElDescriptions,
    ElDescriptionsItem,
  } from 'element-plus'
  import { useLawcaseStore } from '../../store/lawcase'

  /**
   * 格式化日期时间（包含时分秒）
   * @param timestamp 时间戳、日期字符串或Date对象
   * @returns 格式化后的日期时间字符串 (YYYY-MM-DD HH:mm:ss)
   */
  const formatDateTime = (timestamp: any): string => {
    // 检查参数是否有效
    if (!timestamp) {
      return ''
    }

    try {
      let date: Date

      // 检查是否已经是Date对象
      if (timestamp instanceof Date) {
        date = timestamp
      }
      // 如果是数字类型，可能是时间戳
      else if (typeof timestamp === 'number') {
        // 处理时间戳，检查是否需要乘以1000（秒级时间戳转换为毫秒级）
        const finalTimestamp = timestamp.toString().length <= 10 ? timestamp * 1000 : timestamp
        date = new Date(finalTimestamp)
      }
      // 如果是字符串类型
      else if (typeof timestamp === 'string') {
        // 如果是纯数字字符串，认为是时间戳
        if (/^\d+$/.test(timestamp)) {
          const numTimestamp = Number(timestamp)
          const finalTimestamp =
            numTimestamp.toString().length <= 10 ? numTimestamp * 1000 : numTimestamp
          date = new Date(finalTimestamp)
        }
        // 如果是ISO格式的日期字符串，直接解析
        else if (timestamp.includes('T') && timestamp.includes('Z')) {
          date = new Date(timestamp)
        }
        // 如果是普通日期字符串，尝试解析
        else {
          date = new Date(timestamp)
        }
      }
      // 其他类型，直接尝试转换
      else {
        date = new Date(timestamp)
      }

      // 验证日期是否有效
      if (isNaN(date.getTime())) {
        return ''
      }

      // 格式化日期时间
      return date
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
        })
        .replace(/\//g, '-')
    } catch (error) {
      console.error('日期格式化错误:', error, '原始值:', timestamp)
      return ''
    }
  }

  /**
   * 根据诉讼地位返回对应的标签类型
   * @param relationship 诉讼地位ID
   * @returns Element Plus标签类型
   */
  const getRelationshipTagType = (relationship: number): string => {
    const typeMap: { [key: number]: string } = {
      1: 'primary', // 原告
      2: 'danger', // 被告
      3: 'warning', // 第三人
      4: 'primary', // 申请人
      5: 'danger', // 被申请人
      6: 'primary', // 上诉人
      7: 'danger', // 被上诉人
      8: 'primary', // 再审申请人
      9: 'danger', // 被申请人（再审）
      10: 'primary', // 执行申请人
      11: 'danger', // 被执行人
    }
    return typeMap[relationship] || 'info'
  }

  /**
   * 格式化日期（仅年月日）
   * @param date 日期字符串或时间戳
   * @returns 格式化后的日期字符串 (YYYY-MM-DD)
   */
  const formatDate = (date: string | number): string => {
    if (!date) return ''
    const d = new Date(date)
    // 验证日期是否有效
    if (isNaN(d.getTime())) {
      return ''
    }
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }

  // 定义当事人类型
  interface Party {
    id: number
    name: string
    idcard: string
    phone: string
    address: string
    create_time: string
    partyType?: number
    party_type_name?: string // 后端直接返回的类型名称："个人"或"企业"
  }

  interface CaseInfo {
    id: number
    case_code: string
    status: number
    status_text: string
    case_type: number
    case_type_text: string
    clients: string
    opponents: string
    main_lawyer_name: string
    secondary_lawyer_name: string
    session_lawyer_name: string
    session_time: string | number
    contract_id: string
    entrust_date: string
    stage: string
    court_name: string
    case_cause_name: string
    relationship: number
    relationship_text: string
    is_client: number
    is_client_text: string
  }

  // 数据列表
  const partyList = ref<Party[]>([])
  const loading = ref(false)
  const total = ref(0)

  // 初始化store
  const lawcaseStore = useLawcaseStore()

  // 查询表单
  const queryForm = reactive({
    page: 1,
    limit: 10,
    keywords: '',
  })

  // 详情抽屉
  const drawerVisible = ref(false)
  const detailForm = reactive<Party>({
    id: 0,
    name: '',
    idcard: '',
    phone: '',
    address: '',
    create_time: '',
    partyType: 0,
    party_type_name: '',
  })
  const relatedCases = ref<CaseInfo[]>([])
  const casesLoading = ref(false)

  // 编辑对话框
  const dialogVisible = ref(false)
  const dialogTitle = ref('编辑当事人')
  const isEdit = ref(false)

  // 表单数据
  const form = reactive({
    id: 0,
    name: '',
    idcard: '',
    phone: '',
    address: '',
  })

  // 表单验证规则
  const rules = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    idcard: [{ required: true, message: '请输入证件号', trigger: 'blur' }],
  }

  // 表单引用
  const formRef = ref()

  // 获取数据列表
  const getPartyList = async () => {
    loading.value = true
    try {
      const res = await lawcaseStore.getPartyListAction({
        page: queryForm.page,
        limit: queryForm.limit,
        keywords: queryForm.keywords,
      })

      // 修复类型断言，res.data是包含list和total的对象
      const data = res.data as any
      if (res.code === 0 && data && Array.isArray(data.list)) {
        const partyListData = data.list.map((item: any) => ({
          id: item.id,
          name: item.name || item.partyName,
          idcard: item.idcard || item.idNumber,
          phone: item.phone || item.contactPhone,
          party_type_name: item.party_type_name || '', // 直接使用后端返回的类型名称
          address: item.address || '',
          // 同时检查create_time和createTime字段，优先使用非空的那个
          create_time: item.create_time
            ? formatDateTime(item.create_time)
            : item.createTime
              ? formatDateTime(item.createTime)
              : '',
        }))

        partyList.value = partyListData
        // 从res.data.total获取总数
        total.value = data.total || 0
      }
    } catch (error) {
      ElMessage.error('获取当事人列表失败')
    } finally {
      loading.value = false
    }
  }

  // 查询
  const handleQuery = () => {
    queryForm.page = 1
    getPartyList()
  }

  // 重置
  const handleReset = () => {
    queryForm.keywords = ''
    queryForm.page = 1
    getPartyList()
  }

  // 分页
  const handleSizeChange = (val: number) => {
    queryForm.limit = val
    getPartyList()
  }

  const handleCurrentChange = (val: number) => {
    queryForm.page = val
    getPartyList()
  }

  // 查看详情
  const handleView = async (row: Party) => {
    // 填充详情表单数据
    Object.assign(detailForm, row)

    // 获取相关案件列表，使用当事人ID查询
    await getRelatedCases(row.id)

    // 打开抽屉
    drawerVisible.value = true
  }

  // 获取当事人相关案件列表
  const getRelatedCases = async (partyId: number) => {
    if (!partyId) {
      ElMessage.warning('当事人ID不能为空')
      return
    }

    casesLoading.value = true
    relatedCases.value = []
    try {
      // 使用新的API，通过当事人ID查询相关案件
      const response = await lawcaseStore.getRelatedCasesByPartyIdAction(partyId, {
        page: 1,
        limit: 100, // 获取所有相关案件
      })

      if (response.code === 0 && response.data && response.data.list) {
        // 将Lawcase[]转换为CaseInfo[]格式
        relatedCases.value = response.data.list.map((item: any) => ({
          id: item.id,
          case_code: item.case_code,
          status: item.status || 0,
          status_text: item.status_text || '',
          case_type: item.case_type || 0,
          case_type_text: item.case_type_text || '',
          clients: item.clients || '',
          opponents: item.opponents || '',
          main_lawyer_name: item.main_lawyer_name || '',
          secondary_lawyer_name: item.secondary_lawyer_name || '',
          session_lawyer_name: item.session_lawyer_name || '',
          session_time: item.session_time || '',
          contract_id: item.contract_id?.toString() || '',
          entrust_date: item.entrust_date || '',
          stage: item.stage?.toString() || '',
          court_name: item.court_name || '',
          case_cause_name: item.case_cause_name || '',
          relationship: item.relationship || 0,
          relationship_text: item.relationship_text || '',
          is_client: item.is_client || 0,
          is_client_text: item.is_client_text || '',
        }))
      } else {
        relatedCases.value = []
        ElMessage.info('未找到与该当事人相关的案件')
      }
    } catch (error) {
      console.error('获取当事人相关案件失败:', error)
      ElMessage.error('获取当事人相关案件失败')
      relatedCases.value = []
    } finally {
      casesLoading.value = false
    }
  }

  // 编辑
  const handleEdit = (row: Party) => {
    isEdit.value = true
    Object.assign(form, row)
    dialogVisible.value = true
  }

  // 提交表单
  const handleSubmit = () => {
    if (formRef.value) {
      formRef.value.validate(async (valid: boolean) => {
        if (valid) {
          try {
            // 注意：这里需要实现实际的保存API调用
            ElMessage.success('编辑成功')
            dialogVisible.value = false
            getPartyList()
          } catch (error) {
            ElMessage.error('编辑失败')
          }
        }
      })
    }
  }

  // 初始化
  onMounted(() => {
    getPartyList()
  })
</script>

<style scoped>
  .party-container {
    padding: 20px;
    min-height: 100vh;
    background-color: #f5f7fa;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .party-card {
    margin-bottom: 0;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .mb-4 {
    margin-bottom: 16px;
  }

  .table-header-row {
    background-color: #fafafa;
    font-weight: 600;
  }

  .table-row {
    transition: background-color 0.2s;
  }

  .table-row:hover {
    background-color: #f5f7fa;
  }

  .pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }

  .drawer-content {
    padding: 0;
  }

  .related-cases {
    margin-top: 20px;
  }

  .mb-3 {
    margin-bottom: 12px;
  }

  .related-cases h4 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 12px;
  }

  .cell-ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .related-cases .el-table {
    font-size: 14px;
  }
</style>
